package com.htjc.integral.account.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.account.mapper.newdb.EcExtJfWsdlMapper;
import com.htjc.integral.account.service.InvokeBuildOuterService;
import com.htjc.integral.account.util.RedisTem;
import com.htjc.integral.account.util.ResultModel;
import com.htjc.integral.account.util.SoaClient;
import com.htjc.integral.account.util.UrlConfigUtil;
import com.htjc.integral.account.util.XflUtil;
import com.htjc.integral.account.util.enums.AccountReturn;
import com.htjc.integral.account.util.enums.ParamsEnum;
import com.htjc.integral.account.util.enums.ProvinceCodeEnums;
import com.htjc.integral.account.util.enums.RedisKey;
import com.htjc.integral.common.util.JsonUtil;
import com.htjc.integral.common.util.RequestUtils;
import com.htjc.integral.common.util.StrUtil;
import com.htjc.integral.common.util.UUIDGenerator;
import com.htjc.integral.model.conversion.EcExtJfWsdl;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "jfLog")
@Service
public class InvokeBuildOuterServiceImpl implements InvokeBuildOuterService {
	@Autowired
	private EcExtJfWsdlMapper wsdlMapper;
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private RedisTem redisTem;
	@Autowired
	private UrlConfigUtil urlConfigUtil;
	//private final static String passPuterUrl="http://192.168.70.161:17001/integral-interaction-outer/outer/InvokeController/invokeQuery";
	//private final  String passPuterUrl=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_OUT_INVOKEQUERY.getKey());
	@Override
	public JSONObject queryIntegral(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		log.info("调用自建网省查询方法开始=====》参数：{}", jsonObject);
		//		String result = null;
		try {
			log.info("---------自建网省查询方法---------");
			String provinceCode = jsonObject.getString("ORGNO");
			ProvinceCodeEnums[] enums = ProvinceCodeEnums.values();
			Boolean codeReturn=false;
			for (ProvinceCodeEnums ProvinceCodeEnum : enums) {
				if(provinceCode.equals(ProvinceCodeEnum.getShortCode())||provinceCode.equals(ProvinceCodeEnum.getLongCode())) {
					codeReturn=false;
					break;
				}else {
					codeReturn=true;
				}

			}
			//验证网省编码格式
			if(codeReturn) {
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("网省编码错误")));
			}
			log.info("---------自建网省查询方法---------,请求网省={}", provinceCode);
			if (ParamsEnum.ZHEJIANG_LONG.getParamValue().equalsIgnoreCase(provinceCode)
					|| ParamsEnum.ZHEJIANG_SHORT.getParamValue().equalsIgnoreCase(provinceCode)) {
				log.info("进入浙江自建网省积分查询接口====>请求参数={}",jsonObject);
				JSONObject queryScoreDetailZheJiang = queryScoreDetailZheJiang(jsonObject);
				log.info("进入浙江自建网省积分查询接口====>返回结果={}", queryScoreDetailZheJiang);
				return queryScoreDetailZheJiang;
				//				String t=null;
				//				if("1".equals(jsonObject.getString("KAIGUAN"))) {
				//					t=redisTem.get("consNo:"+jsonObject.getString("CONSNO"));
				//				}
				//				if("1".equals(t)) {
				//					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("无划转积分")));
				//				}
				//				redisTem.setex("consNo:"+jsonObject.getString("CONSNO"), 60*60*24, "1");
				//				JSONObject mReturn=new JSONObject();
				//				mReturn.put("BALANCE", "100");
				//				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(mReturn)));
				//				JSONObject json = JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(map)));
				//				log.info("进入浙江自建网省积分查询接口====>返回结果={}", map.toString());
			}else {
				//其他网省
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("非浙江不划转")));
			}

		} catch (Exception e) {
			// TODO: handle exception
			log.error("调用自建网省查询方法异常=====》错误信息：{}", e.getMessage());
		}
		return null;

	}

	@Override
	public JSONObject conversionIntegral(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		log.info("调用自建网省方法开始=====》参数：{}", jsonObject);
		String result = null;
		try {
			log.info("---------自建网省转化方法---------");
			String provinceCode = jsonObject.getString("ORGNO");
			log.info("---------自建网省转化方法---------,请求网省={}", provinceCode);
			if (ParamsEnum.ZHEJIANG_LONG.getParamValue().equalsIgnoreCase(provinceCode)
					|| ParamsEnum.ZHEJIANG_SHORT.getParamValue().equalsIgnoreCase(provinceCode)) {
				log.info("进入浙江自建网省积分查询接口====>请求参数={}",jsonObject);
				JSONObject conversionScoreDetailZheJiang = conversionScoreDetailZheJiang(jsonObject);
				log.info("进入浙江自建网省积分查询接口====>返回结果={}",conversionScoreDetailZheJiang);
				return conversionScoreDetailZheJiang;
				//				String t=null;
				//				if("1".equals(jsonObject.getString("KAIGUAN"))) {
				//					t=redisTem.get("conversiononsNo:"+jsonObject.getString("CONSNO"));
				//				}
				//				if("1".equals(t)) {
				//					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("划转失败")));
				//				}
				//				redisTem.setex("conversiononsNo:"+jsonObject.getString("CONSNO"), 60*60*24, "1");
				//				JSONObject mReturn=new JSONObject();
				//				mReturn.put("score", "100");
				//				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(mReturn)));

				//				JSONObject json = JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(map)));
				//				log.info("进入浙江自建网省积分查询接口====>返回结果={}", map.toString());
			}else {
				//调用其他网省
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("非浙江不划转")));
			}
		} catch (Exception e) {
			// TODO: handle exception
			log.error("调用自建网省方法异常=====》错误信息：{}", e.getMessage());
		}

		log.info("调用自建网省方法结束=====》参数：{}", result);
		return null;
	}

	/**
	 * 调用自建网省方法
	 */
	@Override
	public String doInvoke(JSONObject jsonObject) {
		log.info("调用自建网省方法开始=====》参数：{}", jsonObject);
		String result = null;
		try {

		} catch (Exception e) {
			// TODO: handle exception
			log.error("调用自建网省方法异常=====》错误信息：{}", e.getMessage());
		}

		log.info("调用自建网省方法结束=====》参数：{}", result);
		return result;
	}

	/**
	 * 浙江查询接口
	 * 
	 * @param jsonObject
	 * @return
	 */
	public JSONObject queryScoreDetailZheJiang(JSONObject jsonObject) {
		log.info("调用浙江自建网省查询方法开始=====》参数：{}", jsonObject);
		String passPuterUrl=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_OUT_INVOKEQUERY.getKey());
		//强隔离穿透
		String INTER_ADDRESURL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_ADDRESURL.getKey());
		String result = null;
		String inputXml = "";
		Map<String, Object> mReturn = new HashMap<String, Object>();
		try {

			String consNo = jsonObject.getString("CONSNO");//户号
			String userId = jsonObject.getString("USERID");//userid
			String orgNo = jsonObject.getString("ORGNO"); // 短码
			//			String deOrgNo = orgNo; // 长码
			String loginAccount = jsonObject.getString("LOGIN_ACCOUNT");//登录账号
			ProvinceCodeEnums[] enums = ProvinceCodeEnums.values();
			for (ProvinceCodeEnums ProvinceCode : enums) {
				if(orgNo.length()>=6) {
					if(orgNo.equals(ProvinceCode.getLongCode())) {
						orgNo=ProvinceCode.getShortCode();
						break;
					}
				}else {
					//					orgNo=jsonObject.getString("ORGNO");
					break;
				}

			}
			log.info("---------浙江自建网省查询方法---------,用户ID={},网省编码={},户号={}", userId, orgNo, consNo);
			// 根据户号 和供电单位获取用户信息
			//强隔离调用地址  header
			EcExtJfWsdl jfWsdl = wsdlMapper.getJfWsdl("ZJ_"+orgNo, "ZJ_JFMXCX");
			log.error("queryScoreDetail接口请求配置信息：" + jfWsdl.toString());
			String wsdlurl = jfWsdl.getWsdlAddress();// 请求wsdlurl
			String wsdlHeader = jfWsdl.getZylzd1();// 请求头
			String wsdlData=jfWsdl.getZylzd3();//请求报文拼装
			String acctId = userId;
			String userName = loginAccount;
			//强隔离入参数据
			JSONObject wsdljson=new JSONObject();
			inputXml = "<DBSET><R><C N=\"srvCode\">LSSP_000180</C>" + "<C N=\"channelCode\">ESGCC</C><C N=\"acctId\">"
					+ acctId + "</C><C N=\"userName\">" + userName + "</C><C N=\"consNo\">" + consNo
					+ "</C><C N=\"orgNo\">" + orgNo + "</C></R></DBSET>";

			String input = "<![CDATA[?]]>".replace("?", inputXml);
			log.error("*********强隔离方法请求拼接的参数xml：" + input + ";");
			log.info("********强隔离方法请求拼接的参数getZylzd3：" + wsdlData + ";");
			String jsonData=wsdlData.replace("?", input).replace("*", wsdlurl);
			log.info("********强隔离方法请求拼接的参数data：" + jsonData + ";");
			wsdljson.put("wsdurl", INTER_ADDRESURL);
			wsdljson.put("data", jsonData);
			// 返回结果的result为空 应该是营销的测试接口有问题
			//强隔离调用自建网省webservice
			log.info("********强隔离方法请求拼接的请求参数" + wsdljson.toJSONString());
			String resultStr = RequestUtils.sendPost(passPuterUrl, wsdljson.toJSONString());
			log.info("调用自建网省方法返回值=====》{}",resultStr);
			//outer需要对返回值做处理
			if(resultStr==null||"".equalsIgnoreCase(resultStr)) {
				log.error("调用自建网省方法异常=====》返回为空");
				return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnError(AccountReturn.ACCOUNT_ERROR)));
			}else {
				result = SoaClient.subStringForContent(resultStr.toString(), jfWsdl.getZylzd2());
				List<Map> listr = XflUtil.toList("<DBSET><R>" + result + "</R></DBSET>");
				log.info("调用自建网省方法返回值=====》{}",listr.get(0));
				// 处理如果的rtnCode的返回值0表示成功，1表失败
				if (listr.size() > 0) {
					log.info("调用查询强隔离返回不为空");
					mReturn = listr.get(0);
					// 处理如果的rtnCode的返回值0表示成功，1表失败
					if (mReturn.containsKey("rtnCode")) {
						String rtnCode = String.valueOf(mReturn.get("rtnCode"));
						log.info("调用自建网省方法返回值状态码=====》{}",rtnCode);
						if(!"0".equals(rtnCode)) {
							return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg(mReturn.get("rtnMsg").toString())));
						}
					}
					// 处理积分返回结果，去掉小数
					if (mReturn.containsKey("score")) {
						String score = String.valueOf(mReturn.get("score"));
						score = score.indexOf(".") > -1 ? score.substring(0, score.indexOf(".")) : score;
						if ("".equals(score) || null == score) {
							score = "0";
						}
						mReturn.put("BALANCE", score);
					}

				}else {
					log.info("调用查询强隔离返回为空");
					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("返回值为空")));
				}

			}
		}catch (Exception e) {
			// TODO: handle exception
			log.error("调用自建网省方法异常=====》错误信息：{}", e.getMessage());
		}
		log.info("调用自建网省方法结束=====》参数：{}", mReturn.toString());
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(mReturn)));
	}

	/**
	 * 浙江转化接口
	 * 
	 * @param jsonObject
	 * @return
	 */
	public JSONObject conversionScoreDetailZheJiang(JSONObject jsonObject) {
		String passPuterUrl=urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_OUT_INVOKEQUERY.getKey());
		log.info("调用浙江自建网省划转方法开始=====》参数：{}", jsonObject);
		//强隔离穿透
		String INTER_ADDRESURL = urlConfigUtil.getUrlByKey(RedisKey.URLCON_PREFIXX.getKey(), RedisKey.INTER_ADDRESURL.getKey());
		String acctId = jsonObject.getString("USERID");
		String userName = jsonObject.getString("LOGIN_ACCOUNT");
		String consNo = jsonObject.getString("CONSNO");
		String deOrgNo = null;
		String orgNo = jsonObject.getString("ORGNO"); // 短码
		String score = jsonObject.getString("SCORE");//划转金额
		String goldCoin = jsonObject.getString("GOLDCOIN");
		String checkingid = jsonObject.getString("CHECKINGID");//对账id
		String convertTime = null;
		String id = UUIDGenerator.getInstance().getReplaceUUID();;
		String result = null;
		String inputXml = "";
		String input = "";
		Map<String, Object> mReturn = new HashMap<String, Object>();
		Map<String, String> map = new HashMap<String, String>();
		String success = "false";
		ProvinceCodeEnums[] enums = ProvinceCodeEnums.values();
		for (ProvinceCodeEnums ProvinceCode : enums) {
			if(orgNo.length()>=6) {
				if(orgNo.equals(ProvinceCode.getLongCode())) {
					orgNo=ProvinceCode.getShortCode();
					break;
				}
			}else {
				//					orgNo=jsonObject.getString("ORGNO");
				break;
			}

		}
		try {

			//			1、获取网省的短码///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


			EcExtJfWsdl jfWsdl = this.wsdlMapper.getJfWsdl("ZJ_"+orgNo, "ZJ_JFZH");
			if (!StrUtil.isEmpty(jfWsdl)) {

				log.info("queryScoreConvert接口请求配置信息：" + jfWsdl.toString());
				String wsdlurl = jfWsdl.getWsdlAddress();// 请求wsdlurl
				String wsdlHeader = jfWsdl.getZylzd1();// 请求头
				String wsdlData=jfWsdl.getZylzd3();//请求报文拼装
				//强隔离入参数据
				JSONObject wsdljson=new JSONObject();
				// 请求WSDL
				log.info("********请求WebServicel...START：" + new Date() + ";");
				// 浙江的请求参数与别的网省不一样，单独处理
				userName = userName.length() > 256 ? userName.substring(0, 256) : userName;
				convertTime = sdf.format(new Date());
				inputXml = "<DBSET><R><C N=\"srvCode\">LSSP_000181</C>"
						+ "<C N=\"channelCode\">ESGCC</C><C N=\"acctId\">" + acctId + "</C><C N=\"userName\">"
						+ userName + "</C><C N=\"consNo\">" + consNo + "</C><C N=\"orgNo\">" + orgNo + "</C>"
						+ "<C N=\"score\">" + score + "</C><C N=\"goldCoin\">" + goldCoin + "</C><C N=\"convertTime\">"
						+ convertTime + "</C><C N=\"id\">" + checkingid + "</C>" + "</R></DBSET>";
				input = "<![CDATA[?]]>".replace("?", inputXml);
				log.error("*********强隔离方法请求拼接的参数xml：" + input + ";");
				String jsonData=wsdlData.replace("?", input).replace("*", wsdlurl);
				log.info("********强隔离方法请求拼接的参数data：" + jsonData + ";");
				wsdljson.put("wsdurl",INTER_ADDRESURL);
				wsdljson.put("data", jsonData);
				log.info("********强隔离方法请求拼接的请求参数" + wsdljson.toJSONString());
				String resultStr = RequestUtils.sendPost(passPuterUrl, wsdljson.toJSONString());
				//outer需要对返回值做处理
				if(resultStr==null||"".equalsIgnoreCase(resultStr)) {
					log.error("调用自建网省划转方法异常=====》返回为空");
					return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnError(AccountReturn.ACCOUNT_ERROR)));
				}else {
					result = SoaClient.subStringForContent(resultStr.toString(), jfWsdl.getZylzd2());
					log.info("调用自建网省划转方法返回值=====》{}",result);
					List<Map> listr = XflUtil.toList("<DBSET><R>" + result + "</R></DBSET>");
					log.info("调用自建网省划转方法返回值=====》{}",listr.get(0));
					if (listr.size() > 0) {
						mReturn = listr.get(0);
						// 处理如果的rtnCode的返回值0表示成功，1表失败
						if (mReturn.containsKey("rtnCode")) {
							String rtnCode = String.valueOf(mReturn.get("rtnCode"));
							if(!"0".equals(rtnCode)) {
								return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg(mReturn.get("rtnMsg").toString())));
							}
						}
						// 处理积分返回结果，去掉小数
						if (mReturn.containsKey("score")) {
							String score1 = String.valueOf(mReturn.get("score"));
							score1 = score1.indexOf(".") > -1 ? score1.substring(0, score1.indexOf(".")) : score1;
							if ("".equals(score1) || null == score1) {
								score1 = "0";
							}
							mReturn.put("score", score1);
						}
					}else {
						log.info("调用强隔离返回为空");
						return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnErrorMsg("返回值为空")));
					}
				}

			}

		} catch (Exception e) {
			// TODO: handle exception
			log.error("调用自建网省方法异常=====》错误信息：{}", e.getMessage());
		}
		log.info("调用自建网省方法结束=====》参数：{}", mReturn.toString());
		return JSONObject.parseObject(JsonUtil.bean2json(ResultModel.AccountReturnSucceed(mReturn)));

	}

}
